﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Threading;

namespace WebCgiRoleWordPress
{
    /// <summary>
    /// Summary description for AzureDriveImages
    /// </summary>
    public class AzureDriveImages : IHttpHandler
    {
        public string RealPath
        {
            get
            {
                return WebRole.ImageStorePath;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string year = context.Request.QueryString["year"];
                string month = context.Request.QueryString["month"];
                string filename = context.Request.QueryString["filename"];
                string pathFile = string.Format(@"{0}\{1}\{2}\{3}", RealPath, year, month, filename);

                if (!File.Exists(pathFile))
                {
                    context.Response.Clear();
                    context.Response.StatusCode = 404;
                    context.Response.SuppressContent = true;
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                FileInfo fInfo = new FileInfo(pathFile);
                context.Response.ContentType = string.Format("image/{0}", fInfo.Extension.Replace(".", string.Empty));
                context.Response.StatusCode = 200;
                context.Response.WriteFile(pathFile);
            }
            catch (ThreadAbortException exc)
            {
            }
            catch (Exception ex)
            {
                context.Response.Clear();
                context.Response.StatusCode = 404;
                context.Response.SuppressContent = true;
                context.ApplicationInstance.CompleteRequest(); 
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}